/*
 * SignatureDialog.java
 *
 * Created on __DATE__, __TIME__
 */

package clientPresentation;

import java.io.File;
import javax.swing.JOptionPane;

import utils.Base64Processing;
import utils.SignatureUtils;
import connection.CitizenCardInterface;
import connection.exception.CardErrorException;
import connection.exception.ConnectionResetException;
import client.ClientData;
import client.exceptions.SocketUninitializedException;
import messages.DocumentSigningRequestMessage;
import messages.DocumentSigningResponseMessage;
import messages.NonceToSignRequestMessage;
import messages.NonceToSignResponseMessage;

/**
 *
 * @author  __USER__
 */
@SuppressWarnings("serial")
public class SignatureDialog extends javax.swing.JDialog {

    /**
     * The file that is going to be signed
     */
    private File file;

    /**
     * The Competence to be used in the signature
     */
    private String competence;

    /**
     * Defines whether the VERICOP system is used
     */
    private Boolean vericopEnabled;

    /**
     * Duration for the VERICOP service
     */
    private Integer vericopDuration;

    /** Creates new form SignatureDialog */
    public SignatureDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public SignatureDialog(java.awt.Frame parent, boolean modal, String comp, File sign, Integer duration, boolean vericop) {
        this(parent, modal);

        competence = comp;
        file = sign;
        vericopDuration = duration;
        vericopEnabled = vericop;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    //GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Assinando Ficheiro...");

        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                        .addContainerGap(50, Short.MAX_VALUE)
                        .addComponent(jButton1).addGap(54, 54, 54))
                        .addGroup(
                                layout.createSequentialGroup().addGap(37, 37, 37)
                                .addComponent(jLabel1)
                                .addContainerGap(37, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(
                                javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                Short.MAX_VALUE).addComponent(jButton1)));

        pack();
    }// </editor-fold>
    //GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        setVisible(false);
        dispose();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SignatureDialog dialog = new SignatureDialog(
                        new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    //GEN-BEGIN:variables
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;

    private javax.swing.JLabel jLabel1;

    // End of variables declaration//GEN-END:variables

    public void trySignature() {
        try {

            // Get Signer's First and Last Name
            String[] name = CitizenCardInterface.getFirstLastName();
            String firstName = name[0];
            String lastName = name[1];

            // Ask nonce to Authenticate the Signer
            NonceToSignRequestMessage nRequest = new NonceToSignRequestMessage(firstName, lastName, competence);
            ClientData.getInstance().send(nRequest);
            NonceToSignResponseMessage nResp = (NonceToSignResponseMessage) ClientData.getInstance().receive();

            // Sign the nonce
            Integer nonce = nResp._nonce;
            String valueToSign = nonce + competence;
            String signature = Base64Processing.encodeData(CitizenCardInterface.SignData(valueToSign));

            // Read File into Base64 format
            String fileString = SignatureUtils.readFileToString(file);

            // Send it, along with the competence, and VERICOP data, if needed
            DocumentSigningRequestMessage req = new DocumentSigningRequestMessage(nonce, signature, 
                    competence, fileString, vericopDuration, vericopEnabled);
            ClientData.getInstance().send(req);

            // Receive the signature data
            DocumentSigningResponseMessage res = (DocumentSigningResponseMessage) ClientData.getInstance().receive();

            // Verify if the operation was successful
            Boolean result = res._result;
            if(!result) {
                // Show Dialog and exit
                JOptionPane.showMessageDialog(this, "Ocorreu um erro na opera��o de assinatura:\n" +
                        "-Certifique-se que tem a compet�ncia atribu�da;\n" +
                        "-No caso de escolher verifica��o VERICOP, contacte o administrador para saber se tem permiss�o.");
                return;
            } else {
                // Write New Signature File
                String sigFileString = res._signatureStruct + "\n" + res._docSignature;
                String sigFileName = file.getAbsolutePath()+".certcop";
                SignatureUtils.writeStringToFile(sigFileName, sigFileString);
                
                // Create Zip file, inserting both the Document and the Signature
                String[] zipContents = {file.getAbsolutePath(), sigFileName};
                String archName = file.getAbsolutePath() + "-signed.zip";
                SignatureUtils.compressFiles(archName, zipContents);
                
                // Erase signature file
                File sigFile = new File(sigFileName);
                sigFile.delete();
            }
        } catch (SocketUninitializedException e) {
            e.printStackTrace();
        } catch (ConnectionResetException e) {
            e.printStackTrace();
        } catch (CardErrorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Torna o diálogo invisível e liberta recursos
        setVisible(false);
        dispose();
    }
}